'use strict';

const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken');

class HomeController extends Controller {

    // 登录
    async index() {
        const { ctx, app } = this;
        const { username, password } = ctx.request.body;
        try {
            let token = null;
            let user = await app.mysql.get('user', { username, password })
            if (user) token = jwt.sign(user.username, 'ava')
            if (!user) {
                user = await app.mysql.get('user', { phone: username, password })
                token = jwt.sign(user.phone, 'ava')
            }
            if (!user) {
                user = await app.mysql.get('user', { email: username, password })
                token = jwt.sign(user.email, 'ava')
            }
            ctx.body = {
                token,
                code: 1
            }
        } catch (error) {
            ctx.body = error
        }
    }

    // 注册
    async submit() {
        const { ctx, app } = this;
        const { username, password } = ctx.request.body;
        let email = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        let phone = /^(?:(?:\+|00)86)?1\d{10}$/;
        const root = ''
        if (phone.test((username))) {
            await app.mysql.insert('user', { phone: username, password, username: '', email: '', root })
        } else if (email.test(username)) {
            await app.mysql.insert('user', { email: username, password, phone: 0, username: '', root })
        } else {
            await app.mysql.insert('user', { username, password, phone: 0, email: '', root })
        }
        ctx.body = {
            code: 1
        }
    }
}

module.exports = HomeController;